<template>
  <!-- 类目管理 -->
  <div class="custom-tree-container">
    <el-tree :data="dataSource" node-key="id" :props="props" default-expand-all :expand-on-click-node="false">
      <template #default="{ node, data }">
        <img :src="data.picUrl" class="imgs" />
        <span class="custom-tree-node">
          <span>
            {{ node.label }}
            <el-tag v-if="data.id!=0" :type="forwide(data.level)?.type">{{forwide(data.level)?.title}}</el-tag>
          </span>
          <span>
            <el-space>
              <el-button type="primary" @click="append(data)" round v-if="data.level!=2">添加</el-button>
              <el-button type="warning" @click="amendnew(data)" round v-if="node.level!=1">编辑</el-button>
              <el-button type="danger" round @click="remove( data)" v-if="!data.childrenList">删除</el-button>
            </el-space>
          </span>
        </span>
      </template>
    </el-tree>
    <!-- 弹窗 -->
    <el-dialog v-model="dialogVisible" :title="title" width="600px" :before-close="handleClose">
      <!-- 内容 -->
      <el-form :inline="true" :model="addr" :rules="rules" ref="formName" class="demo-ruleForm" status-icon label-width="120px">
        <el-form-item label="类目名称" prop="title">
          <el-input v-model.trim="addr.title" placeholder="类目名称" />
        </el-form-item>
        <el-form-item label="类目图片" prop="picUrl" v-model="addr.picUrl">
          <el-upload class="avatar-uploader" action="http://192.168.1.188:8080/upload/admin" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" :headers="token">
            <img v-if="addr.picUrl" :src="addr.picUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="resetForm()">取消</el-button>
        <el-button type="primary" @click="title=='创建'? addnew() : editor()">{{title=='创建'? "新增" : "编辑"}}</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { post } from '@/utils/http.js' // 引入封装工具
import { Plus } from '@element-plus/icons-vue'
import jsCookie from "js-cookie";

export default {
  components: { Plus },

  data() {
    return {
      // 数据
      dataSource: [],
      props: {
        children: 'childrenList',
        label: 'title',
      },
      id: '',
      // 弹框数据
      addr: {
        title: '',//类目名称
        picUrl: '',//图片
      },
      adds: {
        title: '',//类目名称
        picUrl: '',//图片
      },
      dialogVisible: false, // 弹出框显示/隐藏
      title: '创建',
      token: {},
      // 表单验证
      rules: {
        title: [
          {
            required: true,
            message: "类目不能为空！"
          }
        ],
      }
    }
  },
  created() {
    this.record() // 调用数据接口
  },
  methods: {
    // 图片
    handleAvatarSuccess(response) {

      this.addr.picUrl = response.url;
    },
    beforeAvatarUpload() {
    },

    forwide(e) {
      switch ((Number(e))) {
        case 0:
          return {
            type: 'danger',
            title: '一级'

          }
          break;
        case 1:
          return {
            type: 'warning',
            title: '二级'

          }
          break;
        case 2:
          return {
            type: 'success',
            title: '三级'

          }
          break;

      }
    },
    // 父类数据
    record() {
      const data = {
        _gp: 'admin.category', // 请求参数
        _mt: 'categoryTree', // 请求参数
      }
      post(data).then((res) => {
        if (200 == res.data.errno) {
          this.dataSource = [
            {
              title: "全部类目",
              childrenList: res.data.data,
            }
          ]
        } else {
          ElMessage.error(res.data.errmsg)
        }
      })
    },

    // 添加弹框
    append(row) {
      this.dialogVisible = true; // 弹出框显示/隐藏
      Object.assign(this.addr, this.adds);
      this.id = row.id
      this.title = '创建'
      this.token = { ADMINTOKEN: jsCookie.get("token") }
    },
    addnew() {
      this.$refs.formName.validate((valid) => {
        if (valid) {
          const data = {
            _gp: "admin.category",
            _mt: "create",
            parentId: this.id,
            ...this.addr,
          };
          post(data).then((res) => {
            if (200 == res.data.errno
            ) {
              ElMessage.success("添加成功");
              this.$refs.formName.resetFields();//清空表单验证
              this.dialogVisible = false; // 弹出框显示/隐藏
              this.record();
            } else {
              ElMessage.error(res.data.errmsg);
            }
          });
        } else {
          ElMessage.error(`验证失败！`);
        }
      });
    },

    // 编辑弹框
    amendnew(row) {
      this.dialogVisible = true; // 弹出框显示/隐藏
      this.title = '编辑'
      Object.assign(this.addr, row)
      this.id = row.id
      this.token = { ADMINTOKEN: jsCookie.get("token") }
    },
    editor() {
      this.$refs.formName.validate((valid) => {
        if (valid) {
          const data = {
            _gp: "admin.category",
            _mt: "update",
            parentId: this.id,
            ...this.addr,
          };
          post(data).then((res) => {
            if (200 == res.data.errno
            ) {
              ElMessage.success("修改成功");
              this.dialogVisible = false; // 弹出框显示/隐藏
              this.record();
            } else {
              ElMessage.error(res.data.errmsg);
            }
          });
        } else {
          ElMessage.error(`验证失败！`);
        }
      });
    },
    // 删除
    remove(e) {
      ElMessageBox.confirm('确认删除?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const data = {
            _gp: 'admin.category', // 请求参数
            _mt: 'delete', // 请求参数
            id: e.id,//ID
          }
          post(data).then((res) => {
            if (200 == res.data.errno) {
              ElMessage.success('删除成功')
              this.record()
            } else {
              ElMessage.error(res.data.errmsg)
            }
          })
        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: '取消操作！'
          })
        })
    },

    // 弹框
    handleClose(done) {
      this.$refs.formName.resetFields();//清空表单验证
      ElMessage({
        type: 'info',
        message: '取消操作！'
      })
        ; (this.dialogVisible = false)
    },

    // 取消
    resetForm() {
      this.$refs.formName.resetFields();//清空表单验证
      ElMessage({
        type: 'info',
        message: '取消操作！'
      })
      this.dialogVisible = false
    },

  }


}
</script>

<style lang="less" scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

/deep/ .el-tree-node__content {
  margin: 20px 0px;
}
.imgs {
  width: 30px;
  margin-right: 10px;
}
</style>
